package com.chen.q4.handler;

import com.chen.q4.filter.HttpRequestFilter;
import com.chen.q4.filter.impl.SimpleHttpRequestFilter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.ReferenceCountUtil;

import java.util.List;

/**
 * @author Charles
 * 接收请求处理器
 */
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {

    private HttpOutboundHandler handler;

    private HttpRequestFilter requestFilter = new SimpleHttpRequestFilter();

    private List<String> proxiedServerList;


    public HttpInboundHandler(List<String> proxiedServerList) {
       this.proxiedServerList = proxiedServerList;
       handler = new HttpOutboundHandler(proxiedServerList);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            FullHttpRequest fullRequest = (FullHttpRequest)msg;
            requestFilter.filter(fullRequest);
            System.out.println(fullRequest.headers().get("inbound_filter"));
            handler.handle(fullRequest,ctx);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }


}
